require "state_machine"

class OrganRegisterRepo < Sequel::Model(:organ_register)
  plugin :validation_helpers
  many_to_one :manager, class: "ManagerRepo"
  
  def validate
    super
    validates_unique   [:manager_id, :organ_id]
    validates_presence [:manager_id, :organ_id]
  end
  


  def perfect
    organ = OrganRepo[organ_id]
    {
      id: id,
      organ: {id: organ.id, name: organ.name},
      manager: {id: manager.id, name: manager.name}
    }
  end


  def self.group(id)
    result = OrganRegisterRepo.where(organ_id: id)
    organ = OrganRepo[id]

    {
      organ: {id: organ.id, name: organ.name},
      managers: result.map do |e|
        e.manager.perfect.merge({register_id: e.id}).tap {|h| h.delete(:state)}
      end
    }
  end
end
